package com.cabd.web.servlet;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.cabd.domain.Folder;
import com.cabd.service.FolderService;
import com.cabd.service.UploadService;
import com.cabd.service.impl.FolderServiceImpl;
import com.cabd.service.impl.UpLoadServiceImpl;
import com.cabd.staticfinal.DownLoadAndUpLoadPath;

//表示可以使用request.getParts()获得上传的文件名
@MultipartConfig
public class FolderServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		String method = request.getParameter("method");
		if(method.equals("upload")) {
			folderUpload(request, response);
		}else if(method.equals("delete")) {
			folderDelete(request, response);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	
	void folderUpload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		//解决文件名中文乱码
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		//获得文件集合，但第一个是目录名，不是文件，所以要剔除
	    Collection<Part> parts = request.getParts();
	    //获得目录名
	    String folderName =  request.getParameter("folderName");
	    String path = DownLoadAndUpLoadPath.downLoadAndUpLoadPath;
	    System.out.println(path);
	    //创建处理文件上传的UploadService
	    UploadService uploadService = new UpLoadServiceImpl();
	    //文件件已存在返回false
	    if(!uploadService.isUpLoad(path, folderName, parts)) {
	    	request.setAttribute("fileUploadInfo", "文件名已存在，请更换文件名！");
	    	request.getRequestDispatcher("/AddFolders.jsp").forward(request, response);
	 	    return;
	    }
	    //文件上传和处理完成
	    request.setAttribute("UpLoadProgress", false);
	    //上传文件返回true
	    request.setAttribute("fileUploadInfo", "文件上传成功!");
	    request.getRequestDispatcher("/AddFolders.jsp").forward(request, response);
	}
	
	
	void folderDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String folderName = request.getParameter("folderName");
		FolderService folderService = new FolderServiceImpl();
		Folder folder = new Folder();
		folder.setFolderName(folderName);
		folderService.deleteDataBase(folder);
		folderService.deleteFiles(folderName);
		response.sendRedirect(request.getContextPath()+"/admin");
	}
	
}